<?php
defined('IN_MAIN') or exit('Invalid Access!');

function calc_stockist_comm($in_date){
/*
This function calculates the stockist commission to a member with stockist status, and any sales that belongs to the group of this stockist
member will be calculated a 10% of sales BV, it will stop until this member has another stockist.
*/

	//globalize access to stockist_comm_percent
	global $vars;
	$db=$vars["db"];
	$stockist_comm_percent = $vars['stockist_comm_percent'];
	$min_maintain = $vars['min_maintain'];
	//calc_date = get the start and end of the input in_date
	$calc_date = get_week_start_end($in_date, 'Y-m-d H:i:s');
	$year = date("Y", strtotime($calc_date['start']));
	$month = date("n", strtotime($calc_date['start']));
	$week = date("W", strtotime($calc_date['end']));
	
	//sales = get all the sales that is confirmed within the date of input in_date
	$t = @mysql_num_rows($r=mysql_query("select * from $db->purchase where status='confirmed' and cdate>='$calc_date[start]' and cdate<='$calc_date[end]'"));
	
	for($i=0;$i<$t;$i++){
		$sale = mysql_fetch_assoc($r);
		$uid = $sale['uid'];
		$level = 0;
		$downline_id = $uid;
		$stockist_id = 0;
		do{
			if (!isset($member_info[$downline_id])){
				$member_info[$downline_id] = get_user_short_detail_by_id($downline_id);
			}
			$upline_id = $member_info[$downline_id]['ref'];
			if ($upline_id){
				if (!isset($member_info[$upline_id])){
					$member_info[$upline_id] = get_user_short_detail_by_id($upline_id);
				}
				if ($member_info[$upline_id]['is_stockist'] == 'y'){
					$stockist_id = $upline_id;
				}
				$downline_id = $upline_id;
				$level += 1;
			}else{
				unset ($downline_id);
			}
		}while ($downline_id && !$stockist_id);
		
		if ($stockist_id){
			$comm_percent = $stockist_comm_percent;
			$comm_amount = round($comm_percent * $sale['amount'] / 100, 2);
			//insert the commission into the member_comm table with type = stockist, cid = sale[id], uid = stockist_id, from_uid = uid, amount = comm_amount, percent = comm_percent, level = level, year, month, datetime
			$sql="insert into $db->member_comm (uid, from_uid, type, cid, amount, level, percent, year, month, week, status, cdate) values ('$stockist_id', '$uid', 't', '$sale[id]', '$comm_amount', '$level', '$comm_percent', '$year', '$month', '$week', 'confirmed', '".ndate('Y-m-d H:i:s')."')";
			$insert_comm_detail="UID: $stockist_id Sale ID: $sale[id] Amount: $comm_amount Level: $level Percent: $comm_percent%<br />\n";
			if(!mysql_query($sql)){
				$insert_error.=$insert_comm_detail."SQL: $sql<br />\n";
			}else{
				$insert_success.=$insert_comm_detail;
			}
			$member_comm[$stockist_id] += $comm_amount;
		}
	}
	
	if ($member_comm){
		foreach ($member_comm as $uid => $amount){	
			if(!mysql_query($sql="update $db->users set ewallet=ewallet+$amount where id='$uid' limit 1")){
				$update_ew_err.="UID: $uid, amount: $amount\n";
			}elseif(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$amount', '".addslashes("Credited $vars[currency]".number_format($amount, 2)." from stockist commission received.")."', '".ndate()."')")){
				$insert_ewrec_err.=$sql."\n";
			}
		}
	}
	
	if($insert_error){
		$status = false;
	}else{
		$status = true;
	}
	
	$errmsg = ($insert_error? "Failed Stockist Commission Calculation:<br />\n<br />\n$insert_error" : "").
	($update_ew_err? "\nError crediting $vars[ewallet_title]:\n\n$update_ew_err" : "").
	($insert_ewrec_err? "\nError crediting $vars[ewallet_title] transactin record:\n\n$insert_ewrec_err" : "");
	
	return array('status'=>$status, 'errmsg'=>$errmsg);
}
?>